<template>
    <Dialog :title="dialogTitle" v-model="dialogVisible" width="90%">
        <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
                v-loading="formLoading"
        >
            <el-form-item label="服务地址" prop="serviceUrl">
                <el-input
                        v-model="formData.serviceUrl"
                        placeholder="请输入服务地址"
                        maxlength="200"
                        show-word-limit
                />
            </el-form-item>
            <el-form-item label="接口路径" prop="interfacePath">
                <el-input
                        v-model="formData.interfacePath"
                        placeholder="请输入接口路径"
                        maxlength="200"
                        show-word-limit
                />
            </el-form-item>
            <el-form-item label="接口类型" prop="interfaceType">
                <el-input v-model="formData.interfaceType" placeholder="请输入接口类型" />
            </el-form-item>
            <el-form-item label="接口方法" prop="interfaceMethod">
                <el-select
                        v-model="formData.interfaceMethod"
                        placeholder="请选择接口方法"
                        clearable
                        class="!w-240px"
                >
                    <el-option
                            v-for="dict in interfaceMethodOptions"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <!-- 新增：接口名称表单项 -->
            <el-form-item label="接口名称" prop="interfaceName">
                <el-input
                        v-model="formData.interfaceName"
                        placeholder="请输入接口名称"
                        maxlength="100"
                        show-word-limit
                />
            </el-form-item>
            <el-form-item label="接口编码" prop="interfaceCode">
                <el-input v-model="formData.interfaceCode" placeholder="请输入接口编码" />
            </el-form-item>
            <el-form-item label="Content-Type类型" prop="contentType">
                <el-input v-model="formData.contentType" placeholder="请输入Content-Type类型" />
            </el-form-item>
            <el-form-item label="请求示例" prop="requestExample">
                <el-input
                        v-model="formData.requestExample"
                        type="textarea"
                        :rows="6"
                        placeholder="请输入请求示例（JSON格式）"
                        @blur="validateJson('requestExample')"
                />
                <div class="flex justify-end mt-8px">
                    <el-button link type="primary" @click="formatJson('requestExample')">
                        格式化
                    </el-button>
                    <el-button link type="primary" @click="clearJson('requestExample')">
                        清空
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="响应示例" prop="responseExample">
                <el-input
                        v-model="formData.responseExample"
                        type="textarea"
                        :rows="6"
                        placeholder="请输入响应示例（JSON格式）"
                        @blur="validateJson('responseExample')"
                />
                <div class="flex justify-end mt-8px">
                    <el-button link type="primary" @click="formatJson('responseExample')">
                        格式化
                    </el-button>
                    <el-button link type="primary" @click="clearJson('responseExample')">
                        清空
                    </el-button>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { InfoApi, Info } from '@/api/base/info'

/** 基础信息 表单 */
defineOptions({ name: 'InfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
// 表单数据：新增interfaceName字段
const formData = ref({
    id: undefined,
    serviceUrl: undefined,
    interfacePath: undefined,
    interfaceType: undefined,
    interfaceMethod: undefined,
    interfaceName: undefined, // 新增：接口名称字段
    interfaceCode: undefined,
    contentType: undefined,
    requestExample: undefined,
    responseExample: undefined,
    remark: undefined
})
// 表单规则：新增interfaceName校验
const formRules = reactive({
    serviceUrl: [{ required: true, message: '服务地址不能为空', trigger: 'blur' }],
    interfacePath: [{ required: true, message: '接口路径不能为空', trigger: 'blur' }],
    interfaceType: [{ required: true, message: '接口类型不能为空', trigger: 'change' }],
    interfaceMethod: [{ required: true, message: '接口方法不能为空', trigger: 'change' }],
    interfaceName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }], // 新增：接口名称校验
    interfaceCode: [{ required: true, message: '接口编码不能为空', trigger: 'blur' }],
    requestExample: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value && value.trim()) {
                    try {
                        JSON.parse(value)
                        callback()
                    } catch (e) {
                        callback(new Error('请求示例必须是有效的JSON格式'))
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    responseExample: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value && value.trim()) {
                    try {
                        JSON.parse(value)
                        callback()
                    } catch (e) {
                        callback(new Error('响应示例必须是有效的JSON格式'))
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})
const formRef = ref() // 表单 Ref

// 接口方法选项（处理类型转换）
const interfaceMethodOptions = computed(() => {
    const intOptions = getIntDictOptions(DICT_TYPE.JIEKOU_TYPE)
    return intOptions.map(option => ({
        ...option,
        value: String(option.value)
    }))
})

/** JSON格式化 */
const formatJson = (field: 'requestExample' | 'responseExample') => {
    if (!formData.value[field]) return

    try {
        const jsonObj = JSON.parse(formData.value[field]!)
        formData.value[field] = JSON.stringify(jsonObj, null, 2)
        message.success('格式化成功')
    } catch (e) {
        message.error('JSON格式错误，无法格式化')
    }
}

/** JSON验证 */
const validateJson = (field: 'requestExample' | 'responseExample') => {
    if (!formData.value[field] || !formData.value[field]!.trim()) return

    try {
        JSON.parse(formData.value[field]!)
    } catch (e) {
        message.error(`${field === 'requestExample' ? '请求示例' : '响应示例'}JSON格式错误`)
    }
}

/** 清空JSON */
const clearJson = (field: 'requestExample' | 'responseExample') => {
    formData.value[field] = undefined
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()

    if (id) {
        formLoading.value = true
        try {
            const info = await InfoApi.getInfo(id)
            formData.value = {
                ...info,
                interfaceMethod: info.interfaceMethod !== null && info.interfaceMethod !== undefined
                    ? String(info.interfaceMethod)
                    : undefined,
                interfaceName: info.interfaceName // 新增：回显接口名称
            }
        } finally {
            formLoading.value = false
        }
    }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
    await formRef.value.validate()
    formLoading.value = true
    try {
        const data = {
            ...formData.value,
            interfaceMethod: formData.value.interfaceMethod ? Number(formData.value.interfaceMethod) : undefined
        } as unknown as Info

        if (formType.value === 'create') {
            await InfoApi.createInfo(data)
            message.success(t('common.createSuccess'))
        } else {
            await InfoApi.updateInfo(data)
            message.success(t('common.updateSuccess'))
        }
        dialogVisible.value = false
        emit('success')
    } finally {
        formLoading.value = false
    }
}

/** 重置表单 */
const resetForm = () => {
    formData.value = {
        id: undefined,
        serviceUrl: undefined,
        interfacePath: undefined,
        interfaceType: undefined,
        interfaceMethod: undefined,
        interfaceName: undefined, // 新增：重置时清空接口名称
        interfaceCode: undefined,
        contentType: undefined,
        requestExample: undefined,
        responseExample: undefined,
        remark: undefined
    }
    formRef.value?.resetFields()
}
</script>
